//
//  LoginMoreOptionsViewController.swift
//  ezyform
//
//  Created by Moennig Q on 21/7/2022.
//  Copyright © 2022 Client.Solution Pty Ltd. All rights reserved.
//

import UIKit
import CryptoSwift
import LocalAuthentication
class LoginMoreOptionsViewController: BaseViewController {
    var refreshMoreOptionsBtnClosure: (()->Void)?
    let customView = LoginMoreOptionsView()
    var localNotificationflag: Bool = false//通知是否已经显示
    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.addSubview(self.customView)
        self.customView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        self.customView.gestureLockView.gestureLockDelegate = self
        self.customView.moreOptionClosure = {[weak self] in
            guard let strongSelf = self else { return }
            strongSelf.customView.showMenuView()
        }
        self.customView.optionsMenuView.selectTypeClosure = { [weak self] (type) in
            guard let strongSelf = self else { return }
            strongSelf.toSelectLoginMethod(type)
        }
        self.customView.startRecognizationClosure = {[weak self] in
            guard let strongSelf = self else { return }
            strongSelf.toLocalAuth()
        }
        self.initData()
        NotificationCenter.default.addObserver(self, selector: #selector(refreshLoginMethod), name: NSNotification.Name(rawValue: "me.loginmethod.setting"), object: nil)
    }
    func initData(){
        self.customView.emailLabel.text = APPConfig.loginInfo.email
        self.customView.dealLoginMethod(APPConfig.loginInfo.currentLoginMethod)
        self.toLocalAuth()
    }
    private func toSelectLoginMethod(_ type: LoginMethodOperation){
        APPConfig.loginInfo.currentLoginMethod = type
        switch type {
        case .faceID,.gesture,.touchID:
            self.customView.dealLoginMethod(type)
            self.toLocalAuth()
        case .password:
            self.dismiss(animated: false) { [weak self] in
                guard let strongSelf = self else { return }
                strongSelf.refreshMoreOptionsBtnClosure?()
            }
        default:
            break
        }
    }
    @objc func refreshLoginMethod(){
        let loginTypes: [LoginMethodOperation] = LoginMethodServcie().getOtherLoginMethod(.password)
        if loginTypes.count == 0 {
            self.dismiss(animated: false) {[weak self] in
                guard let strongSelf = self else { return }
                strongSelf.refreshMoreOptionsBtnClosure?()
            }
        }else{
            if (APPConfig.loginInfo.currentLoginMethod == .touchID || APPConfig.loginInfo.currentLoginMethod == .faceID) && !loginTypes.contains(APPConfig.loginInfo.currentLoginMethod){
                let (_ , errorCode) = LoginMethodServcie().getUsefulBiometryType()
                //是否返回错误
                guard let _ = errorCode else {
                    self.customView.tipLabel.text = ""
                    self.customView.dealRestartBiometry(true)
                    self.customView.hideMenuView()
                    return
                }
                if self.localNotificationflag == false{
                    self.localNotificationflag = true
                    var alertMsg: String = ""
                    let typeStr = LoginMethodServcie().getBiometryTypeName(APPConfig.loginInfo.currentLoginMethod)
                    if errorCode == LAError.Code.biometryLockout {
                        alertMsg = "\(typeStr) is locked by system, please choose another login method"
                    }else if errorCode == LAError.Code.biometryNotEnrolled {
                        alertMsg = "Your \(typeStr) information has changed, please choose another login method"
                    }
                    Tool().showAlertViewWithOneBtn(message: alertMsg) {[weak self] in
                        guard let strongSelf = self else { return }
                        strongSelf.customView.tipLabel.text = alertMsg
                        strongSelf.customView.showMenuView()
                        strongSelf.customView.dealRestartBiometry(false)
                    }
                }
            }
        }
    }
    private func toLocalAuth(){
        if APPConfig.loginInfo.currentLoginMethod == .faceID || APPConfig.loginInfo.currentLoginMethod == .touchID{//生物识别是否成功
            LoginMethodServcie().userLocalAuth() { [weak self] (successFlag,errorType, error) in
                guard let strongSelf = self else {return}
                if successFlag {
                    strongSelf.toLogin()
                }else {
                    //生物识别失效就不显示click here to start了
                    let (biometryType, _) = LoginMethodServcie().getUsefulBiometryType()
                    if biometryType == .none {//
                        strongSelf.customView.dealRestartBiometry(false)
                        //设置不可用
                        LoginMethodServcie().setLoginMethodFlag(APPConfig.loginInfo.currentLoginMethod, isOn: false)
                        strongSelf.customView.showMenuView()
                        let biometryTypeName = LoginMethodServcie().getBiometryTypeName(APPConfig.loginInfo.currentLoginMethod)
                        if errorType == .biometryLockout {//生物识别被锁
                            strongSelf.customView.tipLabel.text = "Too many attempts,\(biometryTypeName) is locked by system, please choose another login method"
                        }else if errorType == .biometryNotEnrolled  {//生物识别数据被删除
                            strongSelf.customView.tipLabel.text = "Your \(biometryTypeName) information has changed, please choose another login method"
                        }
                    }else{
                        //验证失败，或者touch被锁，
                        if errorType == .authenticationFailed || errorType == .biometryLockout {
                            strongSelf.toLocalAuth()
                        }else if errorType == .userFallback {//自定义的user fallback
                            strongSelf.customView.showMenuView()
                        }
                    }
                }
            }
        }
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        DebugLog("\(self) didReceiveMemoryWarning")
    }
}
extension LoginMoreOptionsViewController: GestureLockProtocol {
    func gestureLockSuccess(tagArray: [Int]) {
        let resultPwd = LoginMethodServcie().dealTagArrayToStr(tagArray)
        let gesturePwdCacheKey = LoginMethodServcie().getCacheKey(.gestureSetting)
        if let cacheGesturePwd = UserDefaults.standard.value(forKey: gesturePwdCacheKey) as? String, cacheGesturePwd == resultPwd {//解锁成功
            self.toLogin()
        }else{
            self.customView.gestureLockView.tryUnLockCnt += 1
            let leftCnt = self.customView.gestureLockView.maxUnlockCount - self.customView.gestureLockView.tryUnLockCnt
            if leftCnt > 0 {
                self.customView.tipLabel.text = "Incorrect pattern."
            }else{
                self.customView.tipLabel.text = "Too many attempts, please choose another login method"
                self.customView.showMenuView()//自动弹出菜单
            }
            
        }
        self.customView.gestureLockView.recoverNodeStatus()
    }
    fileprivate func toLogin(){
        LoginMethodServcie().toCheckLogin() {[weak self]  in
            guard let strongSelf = self else {return}
            strongSelf.dismiss(animated: false) {//必须先dismiss，否则controller不释放，造成内存泄漏
                LoginMethodServcie().initRootVC()
            }
        } faildClosure: {  [weak self] (code,errMsg) in
            guard let strongSelf = self else {return}
            Tool().showAlertViewWithOneBtn(message: errMsg, confirmStr: "Use password login") {
                //退出到Login界面，要初始化登录方式为password
                strongSelf.dismiss(animated: false) {
                    //退出到Login界面，要初始化登录方式为password
                    APPConfig.loginInfo.currentLoginMethod = .password
                    strongSelf.refreshMoreOptionsBtnClosure?()
                }
            }
        }
    }
}
